<template>
	<!-- 情况通报创建 -->
	<div>
		<el-form :inline="true" :model="formParams" ref="ruleForm" :rules="rules" class="demo-form-inline" label-position="right" label-width="100px">
			<div class="task">
				<Breadcrumb :Breadcrumb="Breadcrumb"></Breadcrumb>
				<div class="taskhead">
					<div class="taskheadSon">
						<div class="taskMidForm">
							<div>
								<el-form-item label="通报标题:" prop="title">
									<el-input v-model="formParams.title" placeholder="请输入通报标题" style="width: 460px;" clearable></el-input>
								</el-form-item>
							</div>
							<div>
								<el-form-item label="通报范围:" prop="idParams">
									<el-select multiple="" v-model="formParams.idParams" placeholder="请选择" style="width: 460px;">
										<el-option v-for="(item, index) in idParamsOptions" :key="index" :label="item.name" :value="item.id"></el-option>
									</el-select>
								</el-form-item>
							</div>
							<div>
								<el-form-item label="完成时间:" prop="deadline">
									<el-date-picker style="width: 460px;" :picker-options="deadlinePickerOptions" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择完成时间" v-model="formParams.deadline" clearable></el-date-picker>
								</el-form-item>
							</div>
							<div>
								<el-form-item label="汇报内容:" prop="content">
									<quill-editor v-model="formParams.content" />
								</el-form-item>
							</div>
						</div>

					</div>
				</div>
				<!-- 附件组件 -->
				<!-- 情况通报附件上传 -->
				<div style="margin-top:20px;">
					<UploadFile 
						:title ="'情况通报附件上传'" :subTitle ="'文件类型：DOC、DOCX、PDF'" :showUploadButton ="true"
						:maxNumber ="8" :maxSize = "100" :fileTypes ="['DOC', 'DOCX', 'PDF']" 
						:showDleteButton = "true" :fileData = "fileList" :actionUrl = "actionUrl" 
						@deletefile = "deleteFile"
						@uploadsuccess = "uploadSuccess"/>
				</div>
				<!-- 监察建议附件上传 -->
				<div style="margin-top:20px;">
					<UploadFile 
						:title ="'监察建议附件上传'" :subTitle ="'文件类型：DOC、DOCX、PDF'" :showUploadButton ="true"
						:showCustomButton = "true" :customButtonText = "'匹配接收单位'"
						@customevent = "orgMatchAll"
						:botttomExternalShow = 'true' :botttomExternalRender = "orgAttachListExternalRender"
						:maxNumber ="8" :maxSize = "100" :fileTypes ="['DOC', 'DOCX', 'PDF']" 
						:showDleteButton = "true" :fileData = "orgAttachList" :actionUrl = "actionUrl" 
						@deletefile = "deleteOrgFile"
						@uploadsuccess = "uploadOrgSuccess"/>
				</div>
				
				<div class="sureButton">
					<el-form-item>
						<el-button type="reset" @click="reset" style="margin-right: 10px;">取消</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmit" :loading ="submitLoading">提交</el-button>
					</el-form-item>
				</div>
			</div>

		</el-form>
	</div>
</template>
<script>
	import Breadcrumb from "@/components/IncorruptibleArchives/Breadcrumb.vue";
	export default {

		components: {
			Breadcrumb,
			UploadFile: () => import('../../comonComponent/uploadFile')
		},
		data() {
			return {
				submitLoading: false,
				rules:{
					title:[{ required: true, message: '请选填写通报标题', trigger: 'change' }],
					idParams:[{ required: true, message: '请选择通报范围', trigger: 'change' }],
					deadline:[{ required: true, message: '请选择完成时间', trigger: 'change' }],
					content:[{ required: true, message: '请填写汇报内容', trigger: 'change' }],
				},
				formParams: {
					title:'', // 通报标题（必填） 最大长度：255
					idParams: [], // 通报范围（组织ID列表） （列表不能为空）
					deadline: "", // 完成时限（必填）
					content: "", // 通报内容
				},
				idParamsOptions:[],
				Breadcrumb: [{
					name: "监督举报",
					link: "Expenditure"
				}, {
					name: "日常监督",
					link: ""
				}, {
					name: "情况通报",
					link: "Notification"
				}, {
					name: "新建情况通报",
					link: ""
				}],
				fileList: [], //	情况通报附件列表
				orgAttachList:[], // 监察建议书附件列表
				orgAttachListExternalRender:(h, params, data) => { 
						let idParamsOptions = this.idParamsOptions.filter(ele => this.formParams.idParams.includes(ele.id))
						let options = idParamsOptions.map(item => {
							return h('el-option',{props:{value:item.id,label:item.name}})
						})
						return h( 'div', { attrs : { style: 'padding: 6px 15px;display:flex;align-items:center;justify-content: space-between;'}}, [
							h( "span", {style:{display:(this.orgAttachList[params.index].showSelect ? 'none': '')},class:'',attrs : {style: 'width:270px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;',title:params.row.orgName ? params.row.orgName : ''}, props:{}}, '接收单位：' + (params.row.orgName ? params.row.orgName : '')  ),
							h( "span", {style:{display:(this.orgAttachList[params.index].showSelect ? '': 'none')},class:'',attrs : {style: 'width:80px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;'}, props:{}}, '接收单位：'),
							h( "el-select", {style:{display:(this.orgAttachList[params.index].showSelect ? '': 'none')},class:'',attrs : {style: 'width: 190px',multiple: false,}, props:{value: params.row.orgId},on:{
								change: (value) => {
									console.log(value)
									console.log(this.idParamsOptions)
									let org = this.idParamsOptions.find(item => item.id === value)
									console.log(org)
									this.$set(this.orgAttachList[params.index], 'orgId', value)
									this.$set(this.orgAttachList[params.index], 'orgName', org.name)
								}
							}}, options,),
							h( "el-button", { class:'', props:{ size: 'mini',type: 'text'}, on : {
								click : () => {
									this.$set(this.orgAttachList[params.index], 'showSelect', !this.orgAttachList[params.index].showSelect)
									// 选择单位 重新选择接受单位
									this.selectOrg(params.row, params.index)
								}
							} }, params.row.showSelect ? '确认' : params.row.orgName ? '重新选择' : '选择单位' ),
						])
				},
                deadlinePickerOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now()
					}
				},
			};
		},
		computed: {
			//图片获取根路径
			actionUrl() {
				return this.Api.uploadFile;
			},
			
		},
		mounted() {
			this.getNotificationOrgList()
		},
		methods: {
			// 获取接收单位匹配列表数据

			// 获取通报范围下拉列表参数
			getNotificationOrgList() {
				this.Api.getNotificationOrgList().then(res => {
					if (res.code === '0') {
						this.idParamsOptions = res.data
					} else {
						this.idParamsOptions = []
					}
				})
			},
			// 删除文件
			deleteFile (item, index) {
				this.fileList.splice(index, 1)
				this.$message.success(`成功删除文件: ${item.name}`)
			},
			// 文件添加成功
			uploadSuccess (data) {
				this.fileList.push(data)
			},
			// 监察建议附件删除文件
			deleteOrgFile (item, index) {
				this.orgAttachList.splice(index, 1)
				this.$message.success(`成功删除文件: ${item.name}`)
			},
			// 监察建议附件文件添加成功
			uploadOrgSuccess (data) {
				this.orgAttachList.push(data)
			},
			// 单位事件
			orgMatchAll() {
				if (this.formParams.idParams.length === 0) {
					this.$message.warning(`请选择通报范围`)
					return
				}
				if (this.orgAttachList.length === 0) {
					this.$message.warning(`请上传监察建议附件`)
					return
				}
				if (this.formParams.idParams.length === 0 || this.orgAttachList.length === 0) return
				let data = {
					attachNameList: [],
					idParams: []
				}
				
				this.orgAttachList.forEach(item => {
					data.attachNameList.push({attachName: item.name})
				})
				this.formParams.idParams.forEach(item => {
					data.idParams.push({id: item})
				})
				this.Api.getOrgMatchingList(data).then(res => {
					if (res.code === '0') {
						this.orgAttachList = this.orgAttachList.map(item => {
							let matchOrgArray = res.data.filter(matchItem => {
								return matchItem.attachName === item.name
							})
							item.matchOrgArray = matchOrgArray
							if (matchOrgArray.length.length === 0)  return item
							item.orgId = matchOrgArray[0].orgId || ''
							item.orgName = matchOrgArray[0].orgName || ''
							return item
						})
						this.$message.success('匹配接受单位完成')
					}
				})
			},
			// 选择单位
			selectOrg (Item, index) {
				console.log(Item)
				console.log(index)
			},
			//提交
			onSubmit() {
				let validBoolean = false
				this.$refs['ruleForm'].validate(valid => {
					validBoolean = valid
				})
				let attachListCorrect = this.fileList.length === 0
				let orgAttachListCorrect = this.orgAttachList.length === 0
				if (attachListCorrect) {
					this.$message.warning('请选择上传情况通报附件')
					return
				}
				// if (orgAttachListCorrect) {
				// 	this.$message.warning('请选择上传监察建议附件')
				// 	return
				// }
				if(!validBoolean || attachListCorrect) {
					return
				}
				this.submitLoading = true
				let data = JSON.parse(JSON.stringify(this.formParams))
				data.idParams = data.idParams.map(item => { item = {id: item}; return item})
				data.attachList = this.fileList
				data.orgAttachList = this.orgAttachList
				this.Api.doNotificationManageAdd(data).then(res => {
					if (res && res.code === '0') {
						this.$message.warning(`新建情况通报成功`)
						this.$router.go(-1)
					} else{
						this.$message.warning(res.message)
					}
					this.submitLoading = false
				})

			},
			//取消
			reset() {
				console.log("dasdasd222", this.formParams)
				//清空formParams
				this.$router.go('-1')
			},
		}
	};
</script>
<style lang="less" scoped>
	.task {
		width: 100%;
		height: 100%;

		.taskhead {
			background-color: #FFFFFF;

			.taskheadSon {
				padding: 20px;

				.taskMidForm {

				}
			}
		}

		.sureButton {
			padding-top: 24px;
			background-color: #FFFFFF;
			margin-top: 20px;
			height: 56px;
			display: flex;
			justify-content: flex-end;
			align-items: center;

		}
	}

	/deep/.el-button--reset {
		width: 70px;
		height: 36px;
		background: rgba(255, 255, 255, 1);
		border-radius: 3px;
		border: 1px solid rgba(215, 219, 224, 1);
		font-size: 14px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: rgba(51, 51, 51, 1);
		line-height: 22px;
		padding: 0px;
	}

	/deep/.el-button--primary {
		width: 70px;
		height: 36px;
		background: rgba(61, 127, 255, 1);
		font-size: 14px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: rgba(255, 255, 255, 1);
		line-height: 22px;
		padding: 0px;
	}
	
	/deep/.el-icon-date{
		padding-left: 430px;
	}
	/deep/.el-input--prefix .el-input__inner {
	    padding-left: 30px; 
	}
	
</style>
